package DataStructures.栈.栈实现综合运算器;

import DataStructures.栈.数组模拟简单栈.ArrayStack;

import java.util.Stack;

/**
 * @Author: yqy
 * @Date: 2022/03/09/9:55
 * @Description:
 */
public class PulsTest {
    public static void main(String[] args) {
        String s = "13-9/3+4";
        ArrayStackPlus numStack = new ArrayStackPlus(5);
        ArrayStackPlus operStack = new ArrayStackPlus(5);
        int index = 0;
        int num1 = 0, num2 = 0;
        int oper = 0, res = 0;
        String tempStr = "";
        char ch = ' ';
        //入栈并计算优先级高的数
        while (index < s.length()) {
            ch = s.charAt(index);
            //如果是运算符
            if (operStack.isOper(ch)) {
                //操作数栈不为空
                if (!operStack.isEmpty()) {
                    //判断操作数与前一个优先级
                    if (operStack.priority(ch) <= operStack.priority(operStack.peek())) {//当前优先级更小，
                        //取出数据
                        num1 = numStack.pop();
                        num2 = numStack.pop();
                        oper = operStack.pop();
                        res = operStack.cal(num1, num2, oper);
                        //运算结果入栈
                        numStack.push(res);
                        //当前运算符入栈
                        operStack.push(ch);
                    } else {
                        //如果当前操作符大于之前
                        operStack.push(ch);
                    }
                } else {//操作数栈为空
                    //如果是数，则直接入栈
                    operStack.push(ch);
                }
            } else {
                /*直接入栈
                    operStack.push(ch);*/
                //直接入栈只能存一位数，判断下一位数是不是数字，如果是，继续往下扫描，直到结束或者扫描到符号
                tempStr += ch;
                if (index == s.length() - 1) {
                    numStack.push(Integer.parseInt(tempStr));
                } else {
                    if (operStack.isOper(s.charAt(index + 1))) {
                        numStack.push(Integer.parseInt(tempStr));
                        tempStr = "";
                    }
                }
            }
            index++;
        }
        //出栈并计算所有总和
        while (!operStack.isEmpty()) {
            num1 = numStack.pop();
            num2 = numStack.pop();
            oper = operStack.pop();
            res = numStack.cal(num1, num2, oper);
            numStack.push(res);
        }
        System.out.printf("表达式%s=%d", s, numStack.pop());
    }
}
